import React, { useRef } from "react";
import GoBack from "@/components/TheGoBack";
import TheUpload from "@/components/TheUpload";
import { Button, Form, Input, Space, Radio, Timeline, Select } from "antd";
import { apiBannerAdd, apiBannerOne, apiBannerEdit, apiGetLog, apiGetGroupInfo } from '@/request/petCircleUtil/banner'
import { CloseCircleOutlined, PlusOutlined } from '@ant-design/icons';
import { apiActivityLinkList } from "@/request/h5"
import TheTable from "@/components/TheTable";
import "../style/style.less";
import { DndProvider, useDrag, useDrop } from 'react-dnd';
import { HTML5Backend } from 'react-dnd-html5-backend';
import update from 'immutability-helper';

const { Option } = Select
const formItemLayoutWithOutLabel = {
  wrapperCol: {
    xs: { span: 24, offset: 0 },
    sm: { span: 20, offset: 4 },
  },
};
const type = 'DraggableBodyRow';
const DraggableBodyRow = ({ index, moveRow, className, style, ...restProps }) => {
  const ref = useRef(null);
  const [{ isOver, dropClassName }, drop] = useDrop({
    accept: type,
    collect: (monitor) => {
      const { index: dragIndex } = monitor.getItem() || {};
      if (dragIndex === index) {
        return {};
      }
      return {
        isOver: monitor.isOver(),
        dropClassName: dragIndex < index ? ' drop-over-downward' : ' drop-over-upward',
      };
    },
    drop: (item) => {
      moveRow(item.index, index);
    },
  });
  const [, drag] = useDrag({
    type,
    item: {
      index,
    },
    collect: (monitor) => ({
      isDragging: monitor.isDragging(),
    }),
  });
  drop(drag(ref));
  return (
    <tr
      ref={ref}
      className={`${className}${isOver ? dropClassName : ''}`}
      style={{
        cursor: 'move',
        ...style,
      }}
      {...restProps}
    />
  );
};

class Edit extends React.Component {
  constructor(props) {
    super(props);
    this.inputRef = React.createRef();
    this.state = {
      urlType: 1,
      fileList: [],
      logArr: [],
      visible: false,
      btnLoading: false,
      AdID: '',
      fileType: 'image',
      maxSize: 5,
      initialValues: {
        bannerType: 2,
        linkType: 1,
        bannerName: "",
        linkUrl: "",
        bannerImages: "",
        remark: ""
      },
      linkUrl: '',
      activeList: [],
      arr: [],
      columns: [
        {
          title: '群聊ID',
          dataIndex: 'groupId',
          key: 'groupId',
        },
        {
          title: '群聊名称',
          dataIndex: 'groupName',
          key: 'groupName',
        },
        {
          title: '操作',
          dataIndex: 'operate',
          key: 'operate',
          render: (text, record, index) => {
            return (
              <Button type="link" onClick={() => this.handleDelete(index)}> 删除 </Button>
            )
          }
        },
      ],
      dataSource: [],
    };
  }

  async componentDidMount() {
    const { id } = this.props.match.params
    this.getActiveList()
    this.setState({
      AdID: id,
    })
    if (id != 0) {
      await this.getData(id)
    }
    //操作日志
    const rest = await apiGetLog({ dataType: 5, dataId: id })
    if (rest.code === 0 && rest.data) {
      this.setState({
        logArr: rest.data
      })
    }
  }
  async getActiveList() {
    await apiActivityLinkList().then(res => {
      console.log(res);
      if (res.code === 0) {
        this.setState({
          activeList: res.data
        })
      }
    })
  }

  getData = async (bannerId) => {
    let res = await apiBannerOne(bannerId)
    let users = []
    let url = []
    if (res.code === 0 && res.data) {
      let data = res.data
      let fileList = [
        {
          uid: '-1',
          name: 'image.png',
          status: 'done',
          url: data.bannerImages,
        },
      ]
      if (data.linkType !== 3) {
        if (data.linkUrl !== '') {
          this.setState({
            linkUrl: data.linkUrl
          })
        }
      } else {
        if (data.linkUrl.indexOf('?') != '-1') {
          url = data.linkUrl.split('?')
          data.linkUrl = url[0]
          users = url[1].split('&')
          let str = ''
          users.map((item) => {
            str = item.split('=')
            this.state.arr.push({
              key: str[0],
              value: str[1]
            })
          })
        } else {
          data.linkUrl = data.linkUrl.trim()
        }
      }
      this.setState({
        urlType: data.linkType,
        dataSource: JSON.parse(data.content),
        fileList: [...fileList],
      }, () => {
        this.formRef.setFieldsValue({
          ...data,
        })
      })
    }
  }
  //form表单确定事件
  onFinish = async (values) => {
    this.setState({ btnLoading: true })
    if (this.state.AdID === '0') {
      if (values.linkType === 3) {
        let str = ''
        if (values.users && values.users.length !== 0) {
          values.users.map((item, index) => {
            str += item.key + '=' + item.value
            if (index + 1 !== values.users.length) {
              str += '&'
            }
          })
          values.linkUrl = values.linkUrl.trim() + '?' + str
          delete values.users
        } else {
          values.linkUrl = values.linkUrl.trim()
        }
      }
      if (values.linkType === 4 && (values.content === undefined || values.content.length === 0)) {
        React.$message({
          type: 'info',
          content: '请选择群聊'
        })
        this.setState({ btnLoading: false })
        return
      }
      values.content = JSON.stringify(values.content)
      // 添加
      let res = await apiBannerAdd({ ...values })
      if (res.code === 0) {
        React.$message({
          type: 'info',
          content: '添加成功'
        })
        this.props.history.goBack()
      } else {
        this.setState({ btnLoading: false })
      }
    } else {
      if (values.linkType === 2) values.linkNo = ""
      if (values.linkType === 3) {
        let str = ''
        if (values.users && values.users.length !== 0) {
          values.users.map((item, index) => {
            str += item.key + '=' + item.value
            if (index + 1 !== values.users.length) {
              str += '&'
            }
          })
          values.linkUrl = values.linkUrl.trim() + '?' + str
          delete values.users
        } else {
          values.linkUrl = values.linkUrl.trim()
        }
      }
      if(typeof values.content !== 'string'){
        values.content = JSON.stringify(values.content)
      }
      if (values.linkType === 4 && (values.content === undefined || values.content.length === 0)) {
        React.$message({
          type: 'info',
          content: '请选择群聊'
        })
        this.setState({ btnLoading: false })
        return
      }
      // 编辑
      let res = await apiBannerEdit({
        bannerId: this.state.AdID,
        ...values,
      })
      if (res.code === 0) {
        React.$message({
          type: 'info',
          content: '编辑成功'
        })
        this.props.history.goBack()
      } else {
        this.setState({ btnLoading: false })
      }
    }
  }
  // 资源位类型选择
  typeChange = e => {
    console.log(`radio checked:${e.target.value}`);
  }
  //跳转链接类型选择
  urlChange = e => {
    let data = this.formRef.getFieldsValue()
    data.linkUrl = ""
    data.users = []
    data.content = []
    this.formRef.setFieldsValue({
      ...data
    })
    this.setState({
      urlType: e.target.value,
      arr: [],
      dataSource: [],
    })
  }
  onCancel = () => {
    this.setState({
      visible: false
    })
  }

  // 图片上传回调
  getDetailsFileResult = value => {
    if (value && value.length) {
      let arr = value.map(v => {
        if (v.response && v.response.code === 0) {
          return v.response.data
        } else {
          return v.url
        }
      }).join(',')
      this.formRef.setFieldsValue({
        bannerImages: arr
      })
    } else {
      this.formRef.setFieldsValue({
        bannerImages: ""
      })
    }
  }
  configCarouselUriChange = (e) => {
    this.formRef.setFieldsValue({ users: '' })
    this.setState({ linkUrl: e })
  }

  getGroupInfo = async () => {
    const {dataSource} = this.state
    let groupId = this.inputRef.current.input.value
    if (!groupId) {
      React.$message({
        type: 'warning',
        content: '请输入群组ID'
      })
    } else {
      let data = dataSource ? JSON.parse(JSON.stringify(dataSource)): []
      await apiGetGroupInfo({ groupCode:groupId }).then(res => {
        if (res.code === 0) {
          let groupData = {groupId: res.data.groupId, groupName: res.data.groupName}
          data.push(groupData)
          this.setState({
            dataSource: data
          }, () => {
            console.log(this.state.dataSource);
            this.formRef.setFieldsValue({ content: this.state.dataSource })
          })
        }
      })

    }
  }

  handleDelete = (index) => {
    const { dataSource } = this.state;
    let newData = JSON.parse(JSON.stringify(dataSource))
    newData.splice(index, 1);
    this.setState({ dataSource: newData }, () => {
      this.formRef.setFieldsValue({ content: this.state.dataSource })
    });
  }

  // 表格拖拽
  moveRow = () => (dragIndex, hoverIndex) => {
    const { dataSource, LevelCache } = this.state
    const dragRow = dataSource[dragIndex];
    let newData = update(dataSource, {
      $splice: [
        [dragIndex, 1],
        [hoverIndex, 0, dragRow],
      ],
    })
    this.setState({
      dataSource: newData,
    }, () => {
      this.formRef.setFieldsValue({ content: this.state.dataSource })
    });
  }

  render() {
    let {
      initialValues,
      AdID,
      logArr,
      fileList,
      btnLoading,
      fileType,
      maxSize,
      urlType,
      activeList,
      arr, columns, dataSource
    } = this.state;

    return (
      <div className="m-flex">
        <div className="commodity-list-detail p-layout-box" style={{ height: "90vh" }}>
          <GoBack history={this.props.history} title={AdID === '0' ? "新建资源位配置" : "修改资源位配置"} />
          <div className="p-layout-content">
            <Form onFinish={this.onFinish}
              ref={ref => this.formRef = ref}
              labelCol={{
                span: 3,
              }}
              wrapperCol={{
                span: AdID !== '0' ? 9 : 7,
              }}
              initialValues={initialValues}
            >
              <div className="title">基本信息</div>
              <Form.Item rules={[{ required: true }]} label="资源位位类型" name="bannerType">
                <Radio.Group disabled={AdID !== '0'}>
                  <Space>
                    <Radio value={2}>内容首位资源位</Radio>
                    <Radio value={1}>banner区</Radio>
                  </Space>
                </Radio.Group>
              </Form.Item>
              <Form.Item label="资源位名称" name="bannerName">
                <Input placeholder="请输入" />
              </Form.Item>
              <Form.Item rules={[{ required: true }]} label="跳转链接" name="linkType">
                <Radio.Group onChange={this.urlChange} >
                  <Radio value={1}>宠圈动态</Radio>
                  <Radio value={2}>知识库</Radio>
                  <Radio value={3}>H5活动链接</Radio>
                  {/* <Radio value={4}>官方推荐群</Radio> */}
                </Radio.Group>
              </Form.Item>
              {urlType == 1 &&
                <Form.Item style={{ marginLeft: '148px' }} rules={[{ required: true }]} label="" name="linkNo">
                  <Input placeholder="请输入动态编号" />
                </Form.Item>
              }
              {urlType === 3 &&
                <>
                  <Form.Item style={{ marginLeft: '148px' }} rules={[{ required: true }]} label="" name="linkUrl">
                    <Select onChange={this.configCarouselUriChange}>
                      {
                        activeList.map(item => <Option value={item.activityLink} key={item.id}>{item.activityName}</Option>)
                      }
                    </Select>
                    {/* <Input placeholder="请输入链接地址" /> */}
                  </Form.Item>
                  <Form.List name="users" initialValue={arr}>
                    {(fields, { add, remove }) => (
                      <>
                        <Form.Item label="参数">
                          <Button type="dashed" onClick={() => add()} block icon={<PlusOutlined />}>
                            添加参数
                          </Button>
                        </Form.Item>
                        {fields.map(({ key, name, ...restField }) => (
                          <Form.Item
                            {...formItemLayoutWithOutLabel}
                            required={false}
                            key={key}
                            style={{
                              margin: 0
                            }}
                          >
                            <Space
                              style={{
                                display: 'flex',
                                marginBottom: 0,
                              }}
                              align="baseline"
                            >
                              <Form.Item
                                {...restField}
                                name={[name, 'key']}
                                rules={[
                                  {
                                    required: true,
                                    message: '请输入参数名',
                                  },
                                ]}

                              >
                                <Input placeholder="参数名" />
                              </Form.Item>
                              <Form.Item
                                {...restField}
                                name={[name, 'value']}
                                rules={[
                                  {
                                    required: true,
                                    message: '请输入参数值',
                                  },
                                ]}
                              >
                                <Input placeholder="参数值" />
                              </Form.Item>
                              <CloseCircleOutlined onClick={() => remove(name)} />
                            </Space>
                          </Form.Item>
                        ))}

                      </>
                    )}
                  </Form.List>
                </>
              }
              {urlType === 4 && <>
                <Form.Item style={{ marginLeft: '148px' }} >
                  <div style={{ display: 'flex', }}>
                    添加群聊ID <Input ref={this.inputRef} placeholder="请输入" style={{ width: 200, marginLeft: 10, marginRight: 10 }} allowClear /> <Button type="primary" onClick={() => { this.getGroupInfo() }} >添加</Button>
                  </div>
                </Form.Item>
                <Form.Item wrapperCol={{ span: AdID !== '0' ? 11 : 9 }} style={{ marginLeft: '140px' }} name={"content"} label=''  >
                  <DndProvider backend={HTML5Backend}>
                    <TheTable columns={columns} dataSource={dataSource}
                      components={{
                        body: {
                          row: DraggableBodyRow,
                        },
                      }}
                      onRow={(_, index) => {
                        return {
                          index,
                          moveRow: this.moveRow(_, index),
                        };
                      }}
                    />
                  </DndProvider>
                </Form.Item>

              </>}
              <Form.Item rules={[{ required: true }]} label="图片" name="bannerImages"
              >
                {/* extra={`仅限jpg,jpeg,png格式文件，大小不超过${maxSize}M`} */}
                <TheUpload accept={['image/jpg', 'image/jpeg', 'image/png']} {...fileType} maxSize={10}
                  fileList={fileList} getFileResult={this.getDetailsFileResult} len={1} />
              </Form.Item>
              <div className="title">其他信息</div>
              <Form.Item rules={[{ required: false }]} label="备注" name="remark">
                <Input />
              </Form.Item>
              <Form.Item
                wrapperCol={{
                  offset: 4,
                  span: 16,
                }}
              >
                <Space>
                  <Button onClick={() => this.props.history.goBack()}>取消</Button>
                  {/* 添加按钮权限 */}
                  <Button loading={btnLoading} htmlType="submit" type="primary">保存</Button>
                </Space>
              </Form.Item>
            </Form>
          </div>
        </div >
        {
          AdID !== '0' && <div className="commodity-list-detail p-layout-box" style={{ marginLeft: "30px", width: '450px', height: "90vh" }}>
            <div style={{ marginBottom: "20px" }}>操作日志</div>
            <Timeline>
              {
                logArr.map(item => {
                  return (
                    <Timeline.Item>
                      <div>{item.info}
                        <div className="m-flex" ><div>{item.operationUserName}</div><div>{item.operationTime}</div></div>
                      </div>
                    </Timeline.Item>
                  )
                })
              }
            </Timeline>
          </div>
        }
      </div>

    );
  }
}

export default Edit;
